const { Service } = require('egg')
const { tableToList } = require('../utils/tools')

module.exports = class SinfoService extends Service {
  /**
   * * 学籍卡片信息
   * @return {Object} *
   */
  async table() {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/grxx/xsxx`
    const res = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        // 'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const info = {}

    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#xjkpTable')

        /* 处理院系、主专、学制、班级、学号 */
        tableList[2].filter((e) => e).forEach((e) => {
          const tem = e.replace(/\s/g, '').split('：')
          info[tem[0]] = tem[1]
        })

        /* 处理姓名、性别 */
        let key = ''
        tableList[3].filter((e) => e).slice(0, 4).forEach((e, i) => {
          if (i % 2 === 0) {
            info[e] = ''
            key = e
          }
          else info[key] = e
        })

        info['年级'] = tableList[tableList.length - 5][1].slice(0, 4)
        return info
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return info
  }
}
